﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MinhTam.DataAccess.Web;
using MinhTam.Objects;
using System.Data;
using System.IO;
public partial class QuanLyHinhAnh : System.Web.UI.Page
{
    private string display = "none";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            txtMoTa.config.toolbar = HelpUtil.GetSimpleCKEditorConfig(this);
            txtMoTa.config.uiColor = HelpUtil.GetCKEditorUiColorAdmin(this);
            InitData();
            InitListData();
        }
       
    }
    protected string IsVisible()
    {
        if (string.IsNullOrEmpty(keyField.Value))
            return "display:none;";
        return "";
    }
    private void clearnew()
    {
        keyField.Value = "";
        txtMoTa.Text = "";
        txtTenAlbum.Text = "";
     
        btnSave.Text = "Lưu";
        listImage.DataSource = null;
        lblNguoiTao.Text = UserLogin.FULL_NAME(this);
        lblNgayTao.Text = SQLConnectWeb.GetSystemStringDate();
        lblSoAnh.Text = "0";
        lblTitle.Text = "TẠO MỚI ALBUM ẢNH";
        btnDelete.Visible = false;
        listImage.DataSource = null;
        listImage.DataBind();
    }
    private void InitData()
    {
        keyField.Value = Request.QueryString["albumid"];
        string sql = string.Format(@"SELECT aa.ALBUM_ID,u.FULL_NAME  NGUOI_TAO,aa.NGAY_TAO, aa.TEN_ALBUM,aa.MO_TA
        
        FROM ALBUM_ANH aa
        LEFT JOIN USERS u ON u.USERS_ID=aa.NGUOI_TAO
        where aa.ALBUM_ID='{0}' and aa.ALBUM_ID not in {1} ", keyField.Value, HelpConstEnum.FIX_ALBUM);
        DataTable dt = SQLConnectWeb.GetTable(sql);
        if (dt == null || dt.Rows.Count == 0)
        {
            clearnew();

        }
        else
        {
            lblNgayTao.Text = string.Format("{0:dd/MM/yyyy HH:mm:ss}", dt.Rows[0]["NGAY_TAO"]);
            lblNguoiTao.Text = dt.Rows[0]["NGUOI_TAO"].ToString();
            txtMoTa.Text = dt.Rows[0]["MO_TA"].ToString();
            txtTenAlbum.Text = dt.Rows[0]["TEN_ALBUM"].ToString();
            
            btnSave.Text = "Cập nhật album";
            lblTitle.Text = "SỬA ALBUM ẢNH";
            btnDelete.Visible = true;
        }
    }
    private void InitListData()
    {
        lblNoctice.Visible = false;
        if (keyField.Value != "")
        {
            string sql = string.Format(@"SELECT ha.ID,'{0}'+ ha.URL_IMAGE URL_IMAGE ,ha.URL_IMAGE IMAGE_NAME, u.FULL_NAME NGUOI_TAO,
            ha.NGAY_TAO,isnull(ha.IS_ANH_BIA,'N') IS_ANH_BIA
            FROM HINH_ANH ha
            LEFT JOIN USERS u ON u.USERS_ID = ha.NGUOI_TAO
            WHERE ha.Album_ID={1}
            ORDER BY ha.NGAY_TAO", HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER, keyField.Value);
            DataTable dt = SQLConnectWeb.GetTable(sql);
            listImage.DataSource = dt;
            listImage.DataBind();

            if (dt != null) lblSoAnh.Text = dt.Rows.Count.ToString();
        }
     
    }
    protected void btnAnhBia_cLick(object sender, EventArgs e)
    {
        string id = ((Button)sender).CommandArgument;
        string sqlU = string.Format(@"UPDATE HINH_ANH
                SET IS_ANH_BIA =(case when ID={0} then 'Y' else 'N' end)
                WHERE Album_ID={1}", id, keyField.Value);
        SQLConnectWeb.ExecSQL(sqlU);

    }
    protected void btnDel_cLick(object sender, EventArgs e)
    {
        string id = ((Button)sender).CommandArgument;

        string sqlG = "select URL_IMAGE,IS_ANH_BIA from hinh_anh where id=" + id;
        DataTable dt = SQLConnectWeb.GetTable(sqlG);
        if (dt == null || dt.Rows.Count == 0)
        {
            InitListData();
            return;
        }
        string sql = string.Format("delete from HINH_ANH where ID={0}", id);
        if (SQLConnectWeb.ExecSQL(sql))
        {
            if (dt.Rows[0]["IS_ANH_BIA"].ToString() == "Y")
            {
                string sqlU = string.Format(@"UPDATE HINH_ANH
                SET IS_ANH_BIA = 'Y'
                WHERE ID IN (SELECT TOP 1 ha.ID FROM HINH_ANH ha
                WHERE ha.Album_ID={0} ORDER BY ha.ID)", keyField.Value);
                SQLConnectWeb.ExecSQL(sqlU);
            }
            InitListData();
            HelpUtil.DeleteFile(this, HelpConstEnum.UPLOAD_IMAGE_FOLDER + dt.Rows[0]["URL_IMAGE"]);
         
        }
        else
        {
            lblNoctice.Text = "* Xóa ảnh không thành công!";
            lblNoctice.Visible = true;
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        string sql = "";
        if (string.IsNullOrEmpty(keyField.Value))
        {
            sql = @"
            INSERT INTO ALBUM_ANH(	TEN_ALBUM,	NGUOI_TAO,	NGAY_TAO,	MO_TA)
            VALUES(@TEN_ALBUM,@NGUOI_TAO,	getdate(),	@MO_TA	)";
            bool ok = SQLConnectWeb.ExecuteNonQuery(sql,
                                       "@TEN_ALBUM", txtTenAlbum.Text.Trim(),
                                       "@NGUOI_TAO", UserLogin.USER_ID(this),
                                       "@MO_TA", txtMoTa.Text.Replace("'", "")
                                     ) > 0;
            if (ok == false)
            {
                HelpControls.ShowMsgBox(this, "Tạo album không thành công!");
            }
            else
            {
                sql = @"SELECT TOP 1 ALBUM_ID FROM ALBUM_ANH aa
                    ORDER BY aa.ALBUM_ID DESC";
                DataTable dt = SQLConnectWeb.GetTable(sql);
                keyField.Value = dt.Rows[0]["ALBUM_ID"].ToString();
                btnSave.Text = "Cập nhật album";
                btnDelete.Visible = true;
               
                lblTitle.Text = "CẬP NHẬT ALBUM ẢNH";
            }
        }
        else
        {
            sql = @"UPDATE ALBUM_ANH
            SET	TEN_ALBUM =@TEN_ALBUM,	
	            MO_TA = @MO_TA
              where ALBUM_ID=" + keyField.Value;
            bool ok = SQLConnectWeb.ExecuteNonQuery(sql,
                                      "@TEN_ALBUM", txtTenAlbum.Text.Trim(),
                                      "@MO_TA", txtMoTa.Text.Replace("'", "")
                                    ) > 0;
            if (!ok)
            {
                HelpControls.ShowMsgBox(this, "Cập nhật album không thành công!");
            }
        }
    }
    protected void btnCreatNew_Click(object sender, EventArgs e)
    {
        clearnew();
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("QuanLyAlbum.aspx");
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        string sql = string.Format("delete from ALBUM_ANH where ALBUM_ID={0}", keyField.Value);
        if (SQLConnectWeb.ExecSQL(sql))
        {
            Response.Redirect("QuanLyAlbum.aspx");
        }
        else
        {
            HelpControls.ShowMsgBox(this, "Xóa album ảnh không thành công!");

        }
    }
    protected void btnSaveImage_Click(object sender, EventArgs e)
    {
        string UploadPath = Server.MapPath(HelpConstEnum.ADMIN_UPLOAD_IMAGE_FOLDER);
        if (!System.IO.Directory.Exists(UploadPath))
        {
            System.IO.Directory.CreateDirectory(UploadPath);
        }

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        HttpFileCollection uploads = HttpContext.Current.Request.Files;
        string idUser=UserLogin.USER_ID(this);
        int ok = 0;
        string sql1 = "select top 1 is_anh_bia from hinh_hanh where is_anh_bia='Y' and album_id=" + keyField.Value;
        DataTable dt = SQLConnectWeb.GetTable(sql1);
        bool hasanhbia = dt != null && dt.Rows.Count > 0;
        for (int i = 0; i < uploads.Count; i++)
        {
            HttpPostedFile upload = uploads[i];
            string c = System.IO.Path.GetFileName(upload.FileName); ;
            String file_type = System.IO.Path.GetExtension(c).ToLower();
            if (upload.ContentLength == 0)
            {
             
                continue;
            }
            try
            {
                if ((file_type == ".jpg" || file_type == ".gif" || file_type == ".png") && keyField.Value != null)
                {
                    string filename = "IMG_" + DateTime.Now.ToString(HelpConstEnum.ADMIN_FILE_DATEFORMAT) + file_type;       
                

                    upload.SaveAs(UploadPath + filename);
                    //save images path to database
                    string sql = @"INSERT INTO HINH_ANH(URL_IMAGE,	NGUOI_TAO,	NGAY_TAO,	ALBUM_ID,IS_ANH_BIA)
                        VALUES(	@URL_IMAGE, @NGUOI_TAO,getdate(),@ALBUM_ID,@IS_ANH_BIA)";

                    ok += SQLConnectWeb.ExecuteNonQuery(sql,
                                      "@URL_IMAGE", filename,
                                      "@NGUOI_TAO", idUser,
                                      "@ALBUM_ID", keyField.Value,
                                      "@IS_ANH_BIA", hasanhbia ? "N" : "Y");
                    if (ok > 0)
                        hasanhbia = true;


                  

                }
               
               
            }
            catch (Exception ex)
            {
                //sb.AppendLine(String.Format("File: {0} upload failed. Error: {1}...", c, ex.Message.Substring(0, 40)));
                //sb.AppendLine("<br>");
            }
        }

        if (ok == 0) display = "";
        else

            Response.Redirect("QuanLyHinhAnh.aspx?albumid=" + keyField.Value);
     
       
    }
    protected string IsDisplay()
    {
        return "display:" + display;
    }
}
